import path from 'path';
import fs from 'fs';
import os from 'os';
import {
  app,
  BrowserWindow,
  shell,
  ipcMain,
  session,
  dialog,
  MessageChannelMain,
  utilityProcess,
  globalShortcut,
  Menu,
  UtilityProcess,
} from 'electron';
import Store from 'electron-store';
import log from 'electron-log';
import {
  setPathMacId,
  findLogs,
  findUnfinishedTasks,
  batchFailure,
} from './service';
import { resolveHtmlPath } from './util';
import { destroyTray, setUpTray } from './tray';
import configManager from './config';
import { getUserDataPath } from './utils/getUserDataPath';
import MenuBuilder from './menu';
import { updateHandle } from './autoUpdate';
import { DownloadSync } from './syncFile';
import getMAC from 'getmac';

const { port1, port2 } = new MessageChannelMain();

const { port1: port3, port2: port4 } = new MessageChannelMain();


const store = new Store({
  name: 'sync',
  cwd: getUserDataPath(),
});
let user = store.get('user');
// 测试环境

const baseUrl = 'https://syh-test.pinming.org/console/bimfile/';
const baseOrigin = 'https://syh-test.pinming.org';

// const baseUrl = 'https://bim.sepco1.com/console/bimfile/';
// const baseOrigin = 'https://bim.sepco1.com';

// const baseUrl = 'http://localhost:8000/';
// const baseOrigin = 'http://localhost:8000';

// const baseUrl = 'https://zz-test05.pinming.org/console/bimfile/';
// const baseOrigin = 'https://zz-test05.pinming.org';
const isDebug =
  process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true';

if (isDebug) {
  require('electron-debug')();
}

console.log(process.resourcesPath);
const downloadPath = isDebug
  ? path.join(__dirname, './transfer/download.js')
  : path.join(process.resourcesPath, 'app.asar.unpacked/transfer/download.js');

const uploadPath = isDebug
  ? path.join(__dirname, './transfer/upload.js')
  : path.join(process.resourcesPath, 'app.asar.unpacked/transfer/upload.js');

configManager.setEnvConfig({
  baseUrl,
  baseOrigin,
  log: [],
});
configManager.setUpTaskConfig({ tasks: [] });

let mainWindow: BrowserWindow | null = null;

let loginWindow: BrowserWindow | null = null;

let child: UtilityProcess | null = null;

let child2: UtilityProcess | null = null;

const pathWindow: BrowserWindow | null = null;

let willQuitApp = false;

const RESOURCES_PATH = app.isPackaged
  ? path.join(process.resourcesPath, 'assets')
  : path.join(__dirname, '../../assets');

const getAssetPath = (...paths: string[]): string => {
  return path.join(RESOURCES_PATH, ...paths);
};

const findLog = () => {
  return new Promise((resolve) => {
    findLogs({
      mid: user.mid,
      mainId: store.get('mainId'),
    })
      // eslint-disable-next-line promise/always-return
      .then((res) => {
        resolve(res.data?res.data:[]);
      })
      .catch(() => {});
  });
};

const findTasks = () => {
  return new Promise((resolve) => {
    findUnfinishedTasks({
      mid: user.mid,
      mainId: store.get('mainId'),
    })
      // eslint-disable-next-line promise/always-return
      .then((res) => {
        log.info('未完成任务');
        log.info({ res: res.data });
        resolve(res.data?res.data:{});
      })
      .catch(() => {});
  });
};

ipcMain.on('index:openwindow', () => {
  createMainWindow();
});

ipcMain.on('index:closewindow', () => {
  willQuitApp = true;
  mainWindow?.removeAllListeners();
  destroyTray();
  mainWindow?.close();
  mainWindow = null;
  createLoginWindow();
});

ipcMain.on('login:openwindow', () => {
  createLoginWindow();
});

ipcMain.on('login:closewindow', () => {
  loginWindow?.close();
  loginWindow = null;
});

ipcMain.on('get-folder-path', (event) => {
  const folderPath = configManager.getLocal();
  // console.log('获取path', folderPath);
  if (folderPath) {
    event.reply('give-folder-path', folderPath.folderPath);
  }
});
ipcMain.on('get-histroy', (event) => {
  findLog().then((list) => {
    event.reply('get-histroy-list', list);
  });
});

ipcMain.on('path:openwindow', (event) => {
  dialog
    .showOpenDialog({
      properties: ['openDirectory'],
    })
    .then((result) => {
      // eslint-disable-next-line promise/always-return
      if (!result.canceled && result.filePaths.length > 0) {
        if (!result.canceled && result.filePaths.length > 0) {
          const folderPath = result.filePaths[0];
          console.log('选择的文件夹路径：', folderPath);
          event.reply('save-folder-path', folderPath);
        }
      }
    })
    .catch((err) => {
      console.error(err);
    });
  // createPathWindow();
});

ipcMain.on('path:save', (event, path) => {
      // 修改路径后调整mainid

      configManager.updateConfig({ folderPath: path });

      const macAddress = getMAC();
      log.info(`记录本机地址：${macAddress}`);
      setPathMacId({
        mid: user?.mid,
        macAddress,
        storagePath: path,
      })
        // eslint-disable-next-line promise/always-return
        .then((res) => {
          log.info({
            mid: user?.mid,
            macAddress,
            storagePath: path,
          })

          log.info({
            res
          })
          log.info(`记录本机地址mainid：${res.data}`);
          store.set('mainId', res.data);
          port4.postMessage({changePath:true});
          mainWindow?.webContents.send('downsuccess', {});
        })
        .catch((err) => {});

  // event.reply('save-folder-path', path);
});

ipcMain.on('electron-store-get', async (event, val) => {
  event.returnValue = store.get(val);
});

ipcMain.on('electron-store-set', async (event, key, val) => {
  store.set(key, val);
});

ipcMain.on('openExternal', (event, url) => {
  shell?.openExternal(url);
});

ipcMain.on('createfolder', async (event, val) => {
  const folders = val; // 要创建的文件夹名称列表
  folders.forEach((folderName: string) => {
    const folderPath = path.join(
      configManager?.getLocal().folderPath,
      folderName
    ); // 构建文件夹路径

    // 使用 fs 模块的 mkdir 方法来创建文件夹
    fs.mkdir(folderPath, { recursive: true }, (err) => {
      if (err) {
        console.error(`无法创建文件夹 ${folderPath}:`, err);
      } else {
        console.log(`文件夹 ${folderPath} 创建成功`);
      }
    });
  });
});

ipcMain.on('file:upload', async (event, val) => {
  log.info('上传任务手动启动....');

  port4.postMessage({});
});

ipcMain.on('openFolder', async (event, val) => {
  const paths = path.join(configManager.getLocal().folderPath, val);
  shell
    .openPath(paths)
    .then(() => console.log('文件夹已成功打开'))
    .catch((err) => console.error('无法打开文件夹:', err));
});

if (process.env.NODE_ENV === 'production') {
  const sourceMapSupport = require('source-map-support');
  sourceMapSupport.install();
}

ipcMain.on('quit:Task', async (event, val) => {
  batchFailure({
    mid: user.mid,
    mainId: store.get('mainId'),
  }).then((res) => {
    app.quit();
  });
});

const quitApp = () => {
  willQuitApp = false;
  mainWindow = null;
  loginWindow?.close();
  destroyTray();
  child?.kill();
  child2?.kill();
  app.quit();
};
ipcMain.on('index:opertion', async (event, type) => {
  switch (type) {
    case 'close':
      event.preventDefault();
      console.log(store.get('noPrompt'));
      const noPrompt = store.get('noPrompt');

      if (noPrompt == 2) {
        if(store.get('mainId')){
          findTasks().then((res) => {
            // eslint-disable-next-line promise/always-return
            if (
              !res.downloadTasks&&
              !res.uploadTasks
            ) {
              quitApp();
            } else if (mainWindow) {
              mainWindow?.webContents.send('win-quiit-tips', res);
            } else {
              quitApp();
            }
          });
        }else{
          quitApp();
        }

      } else if (noPrompt == 1) {
        mainWindow?.close();
        loginWindow?.minimize();
      } else {
        try {
          mainWindow?.webContents.send('win-close-tips');
          loginWindow?.webContents.send('win-close-tips');
        } catch {}
      }
      break;
    case 'hide':
      mainWindow?.minimize();
      loginWindow?.minimize();

      break;
    case 'full':
      const isFullScreen = mainWindow.isFullScreen();
      mainWindow.setFullScreen(!isFullScreen);

      break;
    case 'quit':
      if(store.get('mainId')){

      findTasks()
        .then((res) => {
          // eslint-disable-next-line promise/always-return
          if (!res.downloadTasks&&
            !res.uploadTasks) {
            quitApp();
          } else if (mainWindow) {
            mainWindow?.webContents.send('win-quiit-tips', res);
          } else {
            quitApp();
          }
        })
        .catch((err) => {});
      }else{
        quitApp();
      }
      break;
    case 'quit2':
        quitApp();
    default:
      break;
  }
});

const installExtensions = async () => {
  const installer = require('electron-devtools-installer');
  const forceDownload = !!process.env.UPGRADE_EXTENSIONS;
  const extensions = ['REACT_DEVELOPER_TOOLS'];

  return installer
    .default(
      extensions.map((name) => installer[name]),
      forceDownload
    )
    .catch(console.log);
};

configManager.setup();

const createLoginWindow = async () => {
  loginWindow = new BrowserWindow({
    width: 400,
    height: 600,
    icon: getAssetPath('icon.png'),
    show: false,
    // title: '工程数字化平台',
    titleBarStyle: 'hiddenInset',
    frame: false,
    maximizable: false,
    resizable: false,
    webPreferences: {
      preload: app.isPackaged
        ? path.join(__dirname, 'preload.js')
        : path.join(__dirname, '../../.erb/dll/preload.js'),
    },
  });

  const env = configManager.getEnvConfig();
  store.set('baseUrl', env.baseUrl);
  store.set('baseOrigin', env.baseOrigin);

  loginWindow.loadURL(resolveHtmlPath('login.html'));

  loginWindow.on('ready-to-show', () => {
    if (!loginWindow) {
      throw new Error('"loginWindow" is not defined');
    }

    if (process.env.START_MINIMIZED) {
      loginWindow.minimize();
    } else {
      loginWindow.show();
    }
  });

  const menuBuilder = new MenuBuilder(loginWindow);
  menuBuilder.buildMenu();

  loginWindow.on('close', (event) => {
    console.log('login:close');
    loginWindow = null;
  });
};

const createMainWindow = async () => {
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 700,
    minHeight: 700,
    minWidth: 1000,
    // titleBarStyle: 'hidden',
    // title: '工程数字化平台',
    icon: getAssetPath('icon.png'),
    show: false,
    titleBarStyle: 'hiddenInset',
    frame: false,
    webPreferences: {
      preload: app.isPackaged
        ? path.join(__dirname, 'preload.js')
        : path.join(__dirname, '../../.erb/dll/preload.js'),
    },
  });
  user = store.get('user');

  const env = configManager.getEnvConfig();
  store.set('baseUrl', env.baseUrl);
  store.set('baseOrigin', env.baseOrigin);

  mainWindow.loadURL(resolveHtmlPath('main.html'));
  updateHandle({ mainWindow });

  mainWindow.on('ready-to-show', () => {
    if (!mainWindow) {
      throw new Error('"mainWindow" is not defined');
    }
    DownloadSync({ port: port2 });

    if (process.env.START_MINIMIZED) {
      mainWindow.minimize();
    } else {
      mainWindow.show();

      if (!child) {
        child = utilityProcess.fork(downloadPath);

        child.on('spawn', () => {
          child?.postMessage({ message: 'hello' }, [port1]);
        });

        port2.on('message', (e) => {
          console.log(e.data);
          const { type, payload } = e.data;
          switch (type) {
            case 'file:download:success':
              // dialog.showMessageBox({
              //   type: 'info',
              //   title: 'Success',
              //   message: '下载成功',
              // });
              mainWindow?.webContents.send('downsuccess', payload);

              console.log('收到刷新列表的消息');
              // try {
              findLog()
                .then((list) => {
                  mainWindow?.webContents.send('get-histroy-list', list);
                })
                .catch(() => {});
              // } catch {}
              break;
            default:
              break;
          }
        });
        port2.start();
      }

      if (!child2) {
        child2 = utilityProcess.fork(uploadPath);

        child2.on('spawn', () => {
          child2?.postMessage({ message: 'hello' }, [port3]);
        });
        port4.on('message', (e) => {
          const { type, payload } = e.data;
          switch (type) {
            case 'file:upload:start':
             log.info('file:upload:start')
              mainWindow?.webContents.send('uploadloading', {
                loading: e.data.loading ?? true,
              });
              break;
              case 'file:upload:empty':
                dialog.showMessageBox({
                  type: 'info',
                  title: '提示',
                  message: '没有检测到待同步的文件',
                });
                break;

            case 'file:delete:refresh':
              mainWindow?.webContents.send('downsuccess', payload);
              findLog()
              .then((list) => {
                mainWindow?.webContents.send('get-histroy-list', list);
              })
              .catch(() => {});
              break;
            case 'file:upload:success':
              dialog.showMessageBox({
                type: 'info',
                title: '成功',
                message: '同步到云端成功',
              });
              // 刷新列表
              mainWindow?.webContents.send('downsuccess', payload);
              mainWindow?.webContents.send('uploadloading', {
                loading: false,
              });
              findLog()
                .then((list) => {
                  mainWindow?.webContents.send('get-histroy-list', list);
                })
                .catch(() => {});
              break;
            default:
              break;
          }
        });

        port4.start();
      }
    }
  });

  mainWindow.on('close', (event) => {
    console.log('mainWindow:close');
    console.log('mainWindow:willQuitApp', willQuitApp);
    if (willQuitApp) {
      willQuitApp = false;
      mainWindow = null;
      destroyTray();
      child?.kill();
      child2?.kill();
    } else {
      // 如果关闭的是主窗口，阻止
      event.preventDefault();

      mainWindow?.webContents.send('win-close-tips');

      // mainWindow?.hide();
    }
  });

  setUpTray(mainWindow);

  const menuBuilder = new MenuBuilder(mainWindow);
  menuBuilder.buildMenu();

  // Open urls in the user's browser
  mainWindow.webContents.setWindowOpenHandler((edata) => {
    shell.openExternal(edata.url);
    return { action: 'deny' };
  });
};

app.on('before-quit', (event) => {
  console.log('app:before-quit');
  willQuitApp = true;
});

app.on('window-all-closed', () => {
  console.log('app:window-all-closed');
  app.quit();
});

const filter = {
  urls: ['http://localhost:*/*'],
};

const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
  app.quit();
}

app
  .whenReady()
  .then(() => {
    session.defaultSession.webRequest.onHeadersReceived(
      filter,
      (details, callback) => {
        const { responseHeaders } = details;
        responseHeaders['Access-Control-Allow-Origin'] = ['*'];
        callback({ responseHeaders });
      }
    );

    store.set('version', app.getVersion());

    if (user?.mid) {
      createMainWindow();
    } else {
      createLoginWindow();
    }

    app.on('activate', () => {
      console.log('app:activate');

      if (mainWindow) {
        mainWindow.restore();
        mainWindow.show();
        // 执行检查更新操作
      }
      if (loginWindow) {
        loginWindow.restore();
        loginWindow.show();
      }
    });

    globalShortcut.register('CommandOrControl+Shift+L', () => {
      const focusWin = BrowserWindow.getFocusedWindow();
      focusWin && focusWin?.toggleDevTools();
    });
  })
  .catch(console.log);

process.on('uncaughtException', (error) => {
  log.error(error.stack || JSON.stringify(error));
  app.exit();
});

export { mainWindow, store };
